
using System;
using System.Collections;
using System.IO;
using System.Diagnostics;

using CStock;
using CUtil;
using CIndicators;


using Microsoft.Win32;
using System.Windows.Forms;
using CUtil.Excel;
using System.Data;

namespace CStock
{
    /// <summary>
    /// Summary description for 
    /// </summary>
    public partial class ProgramContext : StockObjectBase, IProgramContext, IDisposable
    {
     
        #region TradeEconomy Simulation

        //private bool Get_Or_CreateOrderBook()
        //{
        //    if (excelOrderBook != null)
        //    {
        //        return true;
        //    }

        //    DateTime dt = DateTime.Now;


        //    excelOrderBook = new ExcelWriter();
        //    this.excelOrderBook.CreateFile(ProgramContext.Instance.Path + "\\Simulations\\OrderBook_" + dt.ToShortDateString() + ".xls");
        //    return CreateOrderBookWorksheet();


        //}
        private bool CreateOrderBookWorksheet()
        {

            Debug.Assert(excelReader != null);
            if (excelReader == null)
                return false;


            Debug.Assert(excelReader.DataSetExcel != null, "DataSet in Excel reader is null");

            if (excelReader.DataSetExcel == null)
                return false;
            DataTable dataTable = excelReader.DataSetExcel.Tables["OrderBook"];
            if (dataTable != null)
            {
                excelOrderBook.GenerateWorksheet(dataTable, "OrderBook");
                return true;
            }
            else
            {
                excelOrderBook.CloseFile();
                return false;
            }
        }
        //private bool WriteOrdersInOrderBook()
        //{
        //    Get_Or_CreateOrderBook();
        //    if (this.tradeEconomy.StatusReport == null)
        //        this.tradeEconomy.CreateStatusReportBase();

        //    this.excelOrderBook.GenerateWorksheet(this.tradeEconomy.StatusReport, "StatusReport");
        //    return true;

        //}

        private bool PrepareExcelWriter(string excelReadFileName)
        {
            string shortName = string.Empty;
            string dirName = string.Empty;
            CUtil.IOUtil.ExtractDirectoryAndNameFromFileName(excelReadFileName, ref shortName, ref dirName);
            shortName = shortName.Remove(shortName.Length - 4, 4);
            DateTime dt = DateTime.Now;

            if (shortName != string.Empty)
            {
                string zFile = string.Format("Result_{0}_{1:yyyyMMdd}.xls", shortName, dt);
                excelWriter.CreateFile(ProgramContext.Instance.Path + "\\Simulations\\" + zFile);
                return true;
            }
            else
            {
                return false;
            }
        }
        private bool GenerateWorksheet(string worksheetname)
        {
            DataTable dataTable;
            Debug.Assert(excelReader.DataSetExcel != null, "DataSet in Excel reader is null");

            if (excelReader.DataSetExcel == null)
                return false;

            dataTable = excelReader.DataSetExcel.Tables[worksheetname];
            if (dataTable != null)
            {
                excelWriter.GenerateWorksheet(dataTable, worksheetname);
                return true;
            }
            else
            {
                excelWriter.CloseFile();
                return false;
            }
        }
        private bool GenerateAllExcelWorksheets()
        {
            //DataTable dataTable = excelReader.DataSetExcel.Tables["CentralBank"];
            if (GenerateWorksheet("CentralBank"))
            {
                if (GenerateWorksheet("Traders"))
                {
                    if (GenerateWorksheet("Orders"))
                    {
                        if (GenerateWorksheet("Assets"))
                        {
                            if (GenerateWorksheet("Deposits"))
                            {
                                if (GenerateWorksheet("Portfolios"))
                                {
                                    //only at second run, when TradeEconomy is already initialized, write something there
                                    if (tradeEconomy != null)
                                    {
                                        if (this.tradeEconomy.StatusReport == null)
                                            this.tradeEconomy.CreateStatusReportBase();

                                        excelWriter.GenerateWorksheet(this.tradeEconomy.StatusReport, "StatusReport");
                                    }
                                }
                                else
                                {
                                    return false;
                                }




                            }
                            else
                            {
                                return false;
                            }

                        }
                        else
                        {
                            return false;
                        }

                    }
                    else
                    {
                        return false;
                    }

                }
                else
                {
                    return false;
                }

            }
            else
            {
                return false;
            }
            excelWriter.CloseFile();
            return true;
        }
        public bool WriteEconomyInExcel(string excelFileName)
        {
            //gets a template excel file from disk
            //creates a excel file and writes economy in it

            string excelReadTemplate = this.path + "\\Templates\\Economy.xls";
            if (!File.Exists(excelReadTemplate))
            {
                System.Windows.Forms.MessageBox.Show("File does not exist - please get from install package " + excelReadTemplate);
                return false;
            }
            if (excelFileName == null || excelFileName == string.Empty)
            {
                System.Windows.Forms.MessageBox.Show("Excel file is not set when trying to read/write ");
                return false;
            }


            try
            {

                excelReader = new ExcelReader();
                excelWriter = new ExcelWriter();

                excelWriter.CreateFile(excelFileName);

                if (excelReader.ReadExcelFile_SetDataSet(excelReadTemplate))
                {
                    if (GenerateAllExcelWorksheets())
                    {

                        return true;
                    }

                    else
                    {

                        excelWriter.CloseFile();
                        return false;
                    }

                }
                return false;
            }


            catch (Exception ex)
            {
                Debug.Assert(false, "Error in ReadWriteExcel : " + ex.Message);
                return false;
            }
        }
        public bool ReadWriteExcel_Simulations(string excelFileName)
        {
            try
            {
                if (excelFileName == null || excelFileName == string.Empty)
                {
                    System.Windows.Forms.MessageBox.Show("Excel file is not set when trying to read/write ");
                    return false;
                }
                else
                {
                    excelReader = new ExcelReader();
                    excelWriter = new ExcelWriter();


                    if (PrepareExcelWriter(excelFileName))
                    {


                        if (excelReader.ReadExcelFile_SetDataSet(excelFileName))
                        {
                            if (GenerateAllExcelWorksheets())
                            {

                                return true;
                            }
                        }
                        else
                        {

                            excelWriter.CloseFile();
                            return false;
                        }
                    }

                    else
                        return false;
                }
                return true;

            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error in ReadWriteExcel : " + ex.Message);
                return false;
            }
        }


        private bool GetEconomyTradersAndPortfolios()
        {
            try
            {
                //first traders (Portfolios need traders set ...)
                ITraders myTraders = excelReader.GetTraders();
                tradeEconomy.Traders = myTraders;



                IPortfolios myPortfolios = excelReader.GetPortfolios(this.path + "\\Simulations");
                if (myPortfolios != null && myPortfolios.Items.Count > 0)
                {
                    for (int i = 0; i < myPortfolios.Items.Count; i++)
                    {
                        IPortfolio portf = myPortfolios.Items[i] as IPortfolio;
                        ITrader myTrader = CStock.TradeEconomy.GetTraderByID(portf.OwnerID);
                        Debug.Assert(myTrader != null, "Could not fond trader owner for portfolio " + portf.ID);
                        if (myTrader != null)
                            myTrader.Portfolios.Items.Add(portf);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error getting traders and Portfolios from Economy: " + ex.Message);
                return false;

            }

        }
        public bool GetEconomyFromExcelFile(string excelFileName)
        {
            try
            {

                if (ReadWriteExcel_Simulations(excelFileName))
                {
                    this.tradeEconomy = excelReader.GetEconomy_WithoutTraders_Etc();
                    this.tradeEconomy.ExcelFileName = excelFileName;

                    if (GetEconomyTradersAndPortfolios())
                    {


                        tradeEconomy.SetTradeOrdersForEconomyBunds();
                       
                        IOrders orders = excelReader.GetOrders();
                        tradeEconomy.CreateOrderColections(orders);

                        IAssets assets = excelReader.GetAssets();
                        tradeEconomy.SetAssetsToTraders(assets);

                        IDeposits deposits = excelReader.GetDeposits();
                        tradeEconomy.SetDepositsToTraders(deposits);

                        //only here add this - otherwise number of rows is not OK
                        if (this.tradeEconomy.StatusReport == null)
                            this.tradeEconomy.CreateStatusReportBase();

                        //---------------------------------------------------------
                        tradeEconomy.AddStatusReportItem();
                        tradeEconomy.FirstInitIndicators_All();



                        //------------------------------------------------------
                        return true;
                    }
                    else
                        return false;
                }
                else
                {
                    return false;

                }
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error getting economy from Excel : " + ex.Message);
                return false;

            }



        }
        #endregion

    }
}
